const { resolve } = require('path')
const querystring = require('querystring')
const handleBlogRoute = require('./src/routes/blog') //引入blog.js的属性和数据

// 业务代码 这里的数据都会返回给www.js的serverHandler

const getPostData = (req) => {
    const promise = new Promise((resolve, rej) => {
        if (req.method !== 'POST') {
            resolve({})
            return
        }

        if (req.headers['content-type'] !== 'application/json') {
            resolve({})
            return;
        }

        let postData = '';
        req.on('data', (chunk) => {
            postData += chunk.toString();
        });

        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(
                JSON.parse(postData)
            )
        });
    })
    return promise;
}
const serverHandler = (req, res) => { //形参
    //这句话的意思是这个页面返回的是json数据格式的类型
    res.setHeader('Content-Type', 'application/json')

    const url = req.url;
    req.path = url.split('?')[0]

    //解析query
    req.query = querystring.parse(url.split('?')[1])


    getPostData(req).then((postData) => {

        req.body = postData
        //handleBlogRoute是个方法 调用方法填写形参用来处理数据
        const blogDataPromise = handleBlogRoute(req, res);  //调用传入的参数
        if (blogDataPromise) {
            blogDataPromise.then(blogData => {
                res.end(JSON.stringify(blogData));
            })
            return

            // res.end是发送数据给serverHandler  相当于return

        }
        res.writeHead(404, { 'Content-Type': "text/plain" });
        res.write('404 Not Found')
        res.end()
    })

}


//这句话的意思是返回给调用者我们这个页面的全部属性和方法
module.exports = serverHandler